package com.btcode.web.safe.service;

import com.btcode.web.core.unit.URLUtil;
import com.btcode.web.core.unit.WebContext;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletRequest;

public class VerifyService implements IVerifyService {

    /**
     * 免验证地址列表
     */
    private List<String> exceptURL = new ArrayList<>();

    /**
     * 增加例外免验证地址
     */
    public void addExceptURL(String url) {
        exceptURL.add(url);
    }

    @Override
    public Object getUser(ServletRequest request) {
        return WebContext.getSession().getAttribute("userInfo");
    }

    /**
     * 是否可以免验证访问
     */
    public boolean canAccessWithoutAuthentication(ServletRequest request) {

        String requestUrl = URLUtil.getURLWithoutProjectName(request);

        for (String url : exceptURL) {
            if (requestUrl.equals(url)) {
                return true;
            }

            if (url.indexOf("*") >= 0) {
                url = url.replaceAll("/", "\\/").replaceAll("\\*", ".*?");
                Pattern pattern = Pattern.compile("\\/webResource\\/js\\/.*?");
                Matcher matcher = pattern.matcher(requestUrl);
                if (matcher.matches()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 该请求是否可以访问，通过验证
     */
    public boolean canAccess(ServletRequest request) {
        return true;
    }

}
